package cn.wolfcode.web.controller;

import cn.wolfcode.ssm.domain.Department;
import cn.wolfcode.ssm.domain.Employee;
import cn.wolfcode.ssm.domain.Role;
import cn.wolfcode.ssm.page.PageResult;
import cn.wolfcode.ssm.query.EmployeeQueryObject;
import cn.wolfcode.ssm.service.IDepartmentService;
import cn.wolfcode.ssm.service.IEmployeeService;
import cn.wolfcode.ssm.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/employee")

public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IRoleService roleService;

    @RequestMapping("/list")
    public String list(Model model,@ModelAttribute("qo") EmployeeQueryObject qo){
        PageResult<Employee> pageResult = employeeService.query(qo);
        model.addAttribute("pageResult",pageResult);

        List<Department> departments = departmentService.selectAll();
        model.addAttribute("departments",departments);
        return "/employee/list";
    }

    @RequestMapping("/delete")
    public String delete(Long id){
        if (id != null){
            employeeService.delete(id);
        }
        return "redirect:/employee/list.do";
    }

    @RequestMapping("/input")
    public String input(Model model, Long id){
        List<Department> departments = departmentService.selectAll();
        model.addAttribute("departments",departments);
        List<Role> roles = roleService.selectAll();
        model.addAttribute("roles",roles);

        if (id != null){
            Employee employee = employeeService.get(id);
            model.addAttribute("employee",employee);
        }
        return "/employee/input";
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Employee employee, Long[] ids){
        if (employee.getId() != null){
            employeeService.update(employee,ids);
        }else{
            employeeService.save(employee,ids);
        }
        return "redirect:/employee/list.do";
    }

    @RequestMapping("/updatePwd")
    public String updatePwd(){

        return "update/updatePwd";
    }

    @RequestMapping("/reset")
    public String resetPwd(Model model, Long id){
        if (id != null){
            Employee employee = employeeService.get(id);
            model.addAttribute("employee",employee);
        }
        return "reset/resetPwd";
    }


}
